import {StoreCreator,Action,Reducer,Store,Dispatch,Listener,Unsubscribe,Subscribe} from './';

const createStore: StoreCreator = <S, A extends Action<any>, Ext, StateExt>(
  reducer: Reducer<S, A>
  , preloadedState?: S | undefined
): Store<S, A> => {
  let currentState: S = preloadedState as S;
  const currentListeners: Array<Listener> = []; //这里存放着所有监听函数
  function getState(): S{
    return currentState;
  }

  //派发一个动作 所有订阅的组件都会更新(订阅的组件都会触发各自的setState({...}), 也就会触发更新)
  const dispatch: Dispatch<A> = (action: A): A => {
    currentState = reducer(currentState, action);
    currentListeners.forEach(l => l());
    return action; // 99%用不到 react ssr中会用到
  };

  dispatch({type:'@@REDUX/INIT'} as A); // reducer里最后的default 一般会返回默认状态, 故这里就是为了确保仓库状态初始化

  const subscribe: Subscribe = (listener: Listener): Unsubscribe => {
    currentListeners.push(listener);
    return function(){
      const index: number = currentListeners.indexOf(listener);
      currentListeners.splice(index, 1); //从index的位置开始删除 删除一个
    }
  };

  const store: Store<S, A> = {
    getState
    , dispatch
    , subscribe
  };

  return store;
};

export default createStore;
